package com.beamfield.controller.manage.mixstation;

import com.alibaba.fastjson.JSON;
import com.beamfield.common.ApiResult;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.BaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.*;
import com.beamfield.service.manage.mixstation.MixProduceService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拌和站生产管理
 */
@Controller
@RequestMapping(value = "/cms/mixstation/production")
public class MixProduceController extends BaseController {

    private final MixProduceService mixProduceService;

    @Value("${session.beam}")
    private String beam;
    @Value("${session.user}")
    private String user;

    @Autowired
    public MixProduceController(MixProduceService mixProduceService) {
        this.mixProduceService = mixProduceService;
    }
    @RequestMapping(value = "/inbound")
    public ModelAndView production(){
        return new ModelAndView();
    }


    /**
     * 砼拌和
     */
    @RequestMapping(value = "/waitListManage", method = RequestMethod.GET)
    public ModelAndView waitListManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/historyListManage", method = RequestMethod.GET)
    public ModelAndView historyListManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editProductConcrete", method = RequestMethod.GET)
    public ModelAndView editProductConcrete() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/concreteRearatioDetail", method = RequestMethod.GET)
    public ModelAndView concreteRearatioDetail() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/tjzNoticeDetail", method = RequestMethod.GET)
    public ModelAndView tjzNoticeDetail() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/productRearatioDetail", method = RequestMethod.GET)
    public ModelAndView productRearatioDetail() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/warehouseManagement", method = RequestMethod.GET)
    public ModelAndView warehouseManagement() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editWorkOrder", method = RequestMethod.GET)
    public ModelAndView editWorkOrder() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/kaipanzheng", method = RequestMethod.GET)
    public ModelAndView kaipanzheng() {
        return new ModelAndView();
    }
    /**
     * 获取生产任务列表
     * @param offset
     * @param limit
     * @param orderNo
     * @param depart
     *  @param time
     * @return
     */
    @RequestMapping("/getWaitList")
    @ResponseBody
    public PageResult getWaitList(Integer offset, Integer limit, String orderNo, String depart,HttpServletRequest request){
        Long beam_id = super.getBeamId(request);
        return mixProduceService.getWaitList(offset,limit,orderNo,depart, beam_id);
    }
    /**
     * 获取历史任务列表
     * @param offset
     * @param limit
     * @param beam_no
     * @param depart
     *  @param time
     * @return
     */
    @RequestMapping("/getHistoryList")
    @ResponseBody
    public PageResult getHistoryList(Integer offset, Integer limit, String beam_no, String depart, HttpServletRequest request){
        Long beam_id = super.getBeamId(request);
        return mixProduceService.getHistoryList(offset,limit,beam_no,depart,beam_id);
    }
    /**
     * 新增混凝土生产
     *
     * @param object
     * @param mixratioListJson
     * @return
     */
    @RequestMapping("/doEditProductConcrete")
    @ResponseBody
    public ApiResult doEditProductConcrete(String object, String mixratioListJson, HttpSession session) {
        Long user_id = (Long) session.getAttribute(user);
        Long beam_id = (Long) session.getAttribute(beam);

        try {
            MixProductConcrete mixProductConcrete = JSON.parseObject(object,MixProductConcrete.class);
            List<MixProductMixratio> mixProductMixratioList = JSON.parseArray(mixratioListJson, MixProductMixratio.class);
            mixProduceService.insertProductConcrete(mixProductConcrete,mixProductMixratioList,user_id,beam_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }

        return new ApiResult("2", "成功！");
    }
    /**
     * 新增混凝土生产 材料选择
     *
     * @return
     */
    @RequestMapping("/getSuppliesName")
    @ResponseBody
    public ApiResult getSuppliesName(HttpSession session, HttpServletRequest request) {
        ApiResult apiResult = new ApiResult();
        long beamId = (long) session.getAttribute(this.beam);
        String projectId = request.getParameter("projectId");
        List<Supplies> suppliesList = mixProduceService.getSuppliesName(beamId, projectId);
        apiResult.setResult(suppliesList);
        return apiResult;
    }
    /**
     * 砼浇筑通知单详情
     *
     * @param tjz_notice_id
     * @return
     */
    @RequestMapping("/getTjzNoticeInfo")
    @ResponseBody
    public ApiResult getTjzNoticeInfo(Long tjz_notice_id, HttpSession session) {
        ApiResult apiResult = new ApiResult();

        Map<String, Object> map = mixProduceService.getTjzNoticeInfo(tjz_notice_id);

        apiResult.setResult(map);
        return apiResult;
    }
    /**
     * 混凝土配料通知单详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/getConcreteRearatioInfo")
    @ResponseBody
    public ApiResult getConcreteRearatioInfo(Long id, HttpSession session) {
        ApiResult apiResult = new ApiResult();

        ConcreteRearatio concreteRearatio = mixProduceService.getConcreteRearatioInfo(id);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("concreteRearatio",concreteRearatio);

        apiResult.setResult(map);
        return apiResult;
    }
    /**
     * 获取生产施工配合比
     * @param request
     * @return
     */
    @RequestMapping(value = "/readProMixratioData", method = RequestMethod.GET)
    @ResponseBody
    public PageResult readProMixratioData(HttpServletRequest request){
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String concreteRearatioId = request.getParameter("concrete_rearatio_id");
        if(StringUtils.isEmpty(concreteRearatioId)){
            return null;
        }
        return mixProduceService.getProMixratioData(offset, limit, concreteRearatioId);
    }

    /**
     * 砼检测
     */
    @RequestMapping(value = "/todayDetectListManage", method = RequestMethod.GET)
    public ModelAndView todayDetectListManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/historyDetectListManage", method = RequestMethod.GET)
    public ModelAndView historyDetectListManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editConcreteDetect", method = RequestMethod.GET)
    public ModelAndView editConcreteDetect() {
        return new ModelAndView();
    }
    /**
     * 获取今日检测任务列表
     * @param offset
     * @param limit
     * @param beam_no
     * @param tjz_no
     * @return
     */
    @RequestMapping("/getTodayDetectList")
    @ResponseBody
    public PageResult getTodayDetectList(Integer offset, Integer limit, String beam_no,String tjz_no, HttpServletRequest request){
        Long beam_id = super.getBeamId(request);
        return mixProduceService.getTodayDetectList(offset,limit,beam_no,tjz_no,beam_id);
    }
    /**
     * 获取历史检测任务列表
     * @param offset
     * @param limit
     * @param beam_no
     * @param tjz_no
     *  @param detect_date
     * @return
     */
    @RequestMapping("/getHistoryDetectList")
    @ResponseBody
    public PageResult getHistoryDetectList(Integer offset, Integer limit, String beam_no, String tjz_no, String detect_date, HttpServletRequest request){
        Long beam_id = super.getBeamId(request);
        return mixProduceService.getHistoryDetectList(offset,limit,beam_no,tjz_no,detect_date,beam_id);
    }
    /**
     * 新增检测任务
     *
     * @param mixConcreteDetect
     * @return
     */
    @RequestMapping("/doEditConcreteDetect")
    @ResponseBody
    public ApiResult doEditConcreteDetect(MixConcreteDetect mixConcreteDetect, HttpSession session) {
        Long user_id = (Long) session.getAttribute(user);
        Long beam_id = (Long) session.getAttribute(beam);

        try {
            ApiResult apiResult = mixProduceService.isSuppliesEnough(mixConcreteDetect.getConcrete_rearatio_id(),mixConcreteDetect.getSquare(),beam_id);
            if(apiResult.getCode().equals("1")){
                return apiResult;
            }
            mixProduceService.insertConcreteDetect(mixConcreteDetect,user_id,beam_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }

        return new ApiResult("2", "成功！");
    }
    /**
     * 获取施工配料通知单
     * @return
     */
    @RequestMapping("/getAllConcreteRearatio")
    @ResponseBody
    public List<ConcreteRearatio> getAllConcreteRearatio(HttpServletRequest request){
        Long beam_id = super.getBeamId(request);
        return mixProduceService.getAllConcreteRearatio(beam_id);
    }
    /**
     * 导出砼拌和任务
     *
     * @param response
     * @param offset
     * @param limit
     * @param beam_no
     * @param depart
     * @param time
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportWaitList")
    @ResponseBody
    public String exportWaitList(HttpServletResponse response, Integer offset, Integer limit,String orderNo, String depart, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return mixProduceService.exportWaitList(response,offset,limit,orderNo,depart,beam_id);
    }
    /**
     * 导出砼拌和历史任务
     *
     * @param response
     * @param offset
     * @param limit
     * @param beam_no
     * @param depart
     * @param time
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportHistoryList")
    @ResponseBody
    public String exportHistoryList(HttpServletResponse response, Integer offset, Integer limit,String beam_no, String depart, String time, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return mixProduceService.exportHistoryList(response,offset,limit,beam_no,depart,time,beam_id);
    }
    /**
     * 导出砼检测任务
     *
     * @param response
     * @param offset
     * @param limit
     * @param beam_no
     * @param tjz_no
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportTodayDetect")
    @ResponseBody
    public String exportTodayDetect(HttpServletResponse response, Integer offset, Integer limit,String beam_no, String tjz_no, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return mixProduceService.exportTodayDetect(response,offset,limit,beam_no,tjz_no,beam_id);
    }
    /**
     * 导出砼检测历史任务
     *
     * @param response
     * @param offset
     * @param limit
     * @param beam_no
     * @param tjz_no
     * @param detect_date
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportHistoryDetect")
    @ResponseBody
    public String exportHistoryDetect(HttpServletResponse response, Integer offset, Integer limit,String beam_no, String tjz_no, String detect_date, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return mixProduceService.exportHistoryDetect(response,offset,limit,beam_no,tjz_no,detect_date,beam_id);
    }

    /**
     * 获取生产
     * @param concrete_rearatio_id
     * @return
     */
    @RequestMapping(value = "/getMixProductConcrete", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getMixProductConcrete(String concrete_rearatio_id){
        if(StringUtils.isEmpty(concrete_rearatio_id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        return mixProduceService.getMixProductConcrete(concrete_rearatio_id);
    }

    /**
     * 解析html
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/analyzeMakeOrderHtml", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult analyzeMakeOrderHtml(HttpServletRequest request,@RequestParam("file") MultipartFile multipartFile){
        if(multipartFile.isEmpty()){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
            Document document = Jsoup.parse(inputStream, "UTF-8", "");
            return new ApiResult(mixProduceService.analyzeMakeOrder(document));
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取未添加到工单中的开盘证列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/getOpening", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getOpening(HttpServletRequest request){
        Long beamId = super.getBeamId(request);
        return new ApiResult(mixProduceService.getOpening(beamId));
    }

    /**
     * 保存工单信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveWorkOrder", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveWorkOrder(HttpServletRequest request){
        String dataJson = request.getParameter("dataJson");
        String openings = request.getParameter("openings");
        if(StringUtils.isBlank(dataJson)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long beamId = super.getBeamId(request);
        Long userId = super.getUserId(request);
        try{
            MixTzWorkorder workorder = JSON.parseObject(dataJson, MixTzWorkorder.class);
            if(workorder.getId() != null){
                mixProduceService.delWorkOrderOpening(workorder.getId());
            }
            workorder.setOperator(userId);
            workorder.setAddtime(new Date());
            workorder.setBeam_id(beamId);
            Long id = mixProduceService.saveWorkOrder(workorder);
            if(StringUtils.isNotBlank(openings)){
                mixProduceService.saveWorkorderOpening(openings, id, beamId, userId);
            }
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 删除工单
     * @param request
     * @return
     */
    @RequestMapping(value = "/delWorkOrder", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult delWorkOrder(HttpServletRequest request){
        String id = request.getParameter("id");
        if(StringUtils.isBlank(id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        mixProduceService.delWorkOrderOpen(Long.parseLong(id));
        return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "删除成功");
    }

    /**
     * 根据工单id获取工单和开盘证
     * @param request
     * @return
     */
    @RequestMapping(value = "/getWorkOrder", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getWorkOrder(HttpServletRequest request){
        String id = request.getParameter("id");
        if(StringUtils.isBlank(id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        return new ApiResult(mixProduceService.getWorkOrder(Long.parseLong(id)));
    }

    @RequestMapping("/importExcel")
    @ResponseBody
    public ApiResult importExcel(HttpServletRequest request, @RequestParam("excelFile") MultipartFile multipartFile){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        if (multipartFile == null) {
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try {
            long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            InputStream in = multipartFile.getInputStream();
            byte[] data = IOUtils.toByteArray(in);
            Workbook wb = null;
            FormulaEvaluator formulaEvaluator;
            try {
                wb = new HSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
            } catch (Exception e) {
                wb = new XSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
            }
            return mixProduceService.importExcel(wb, fileId, userId, beamId, formulaEvaluator);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), e.getMessage());
        }
    }
}
